import 'dart:io';
import 'dart:typed_data';

import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:example/utils/common.dart';
import 'package:example/utils/local_manage.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

/// File 扩展
extension FileExt on File {
  /// 获取后缀名
  String getFileSuffix() {
    return getFullFileName().split(".").last;
  }

  /// 获取文件名
  String getFileName() {
    return getFullFileName().split(".").first;
  }

  /// 获取文件名包含后缀名
  String getFullFileName() {
    return path.split("/").last;
  }

  /// 转图片选择器数据对象
  Future<AssetEntity?> toAssetEntity() async {
    PermissionStatus status = await Permission.storage.status;
    if (status.isDenied || status.isPermanentlyDenied) {
      showToast("请打开存储权限后重试");
      return Future.error("请打开存储权限后重试");
    }
    final Uint8List byteData = await readAsBytes();
    return await PhotoManager.editor.saveImage(byteData, title: '');
  }

  Future<File?> compressFile() async {
    String cachePath = await LocalManage.getCachePath();

    FlutterImageCompress.validator.ignoreCheckExtName = true;
    String suffix = getFileSuffix();
    File? result = await FlutterImageCompress.compressAndGetFile(
      absolute.path,
      "$cachePath/${getFileName()}_${DateTime.now().millisecondsSinceEpoch}.$suffix",
      quality: 88,
    );

    return result;
  }
}

/// XFile 扩展
extension XFileExt on XFile {
  File toFile() {
    return File(path);
  }
}
